# -*- coding: UTF-8 -*-
import sys
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, session,Blueprint
import os
import json
import re
import dbase
import conf_parser
import decimal
import datetime
import webbrowser
from data import data

app = Flask(__name__)
app.secret_key = "1qa@WS3edc"
app.register_blueprint(data,url_prefix='/')
app.debug = True

@app.route("/execute",methods=["POST"])
def execute():
    sql = request.values.get("sql")
    i = sql.lower().find("insert")
    j = sql.lower().find("into")
    n = sql.lower().find("update")
    if i>=0 and j>=0:
        v = dbase.insert(sql)
    elif n>=0:
        v = dbase.update(sql)
    else:
        v = dbase.query(sql)

    class DecimalEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, decimal.Decimal):
                return float(o)
            if isinstance(o, datetime.datetime):
                return o.strftime("%Y-%m-%d %H:%M:%S")
            super(DecimalEncoder, self).default(o)

    return json.dumps(v,cls=DecimalEncoder,ensure_ascii=False)

@app.route("/",methods=["GET","POST"])
def index():
    data = request.args.get("data")
    if data == None:
        data = ""
    return render_template("index.html",data=data)

@app.route("/<html>",methods=["GET","POST"])
def f(html):
    data = request.args.get("data")
    if data==None:
        data = ""
    return render_template(html,data=data)

@app.route("/setSession",methods=["POST"])
def setSession():
    key = request.values.get("key")
    value = request.values.get("value")
    session[key] = value
    return "OK"

@app.template_global()
def getId(str):
    sql = "select nextval('"+str+"')"
    v = dbase.query(sql)
    return v[0][0]

@app.template_global()
def split(str,flag):
    return str.split(flag)

@app.template_global()
def set(key,value):
    session[key]=value

@app.template_global()
def getSession(key):
    str = ""
    try:
        str = session[key]
    except Exception as a:
        print(a)
    return str

def resource_path(relative_path):
    base_path = conf_parser.getValue('server', 'file_path')
    return os.path.join(base_path, relative_path)

def kill_process():
    ret = os.popen("netstat -nao|findstr " + str(serverport))
    str_list = ret.read()
    print(str_list)
    ret_list = re.split('[\s]',str_list)
    try:
        process_pid = ret_list[len(ret_list)-2]
        os.popen('taskkill /pid ' + str(process_pid) + ' /F')
        print("端口已被释放")
    except:
        print("端口未被使用")

# 入口函数
if __name__ == "__main__":
    serverip = "0.0.0.0"
    conf_parser.init()
    serverport = conf_parser.getValue('server', 'port')
    robot = conf_parser.getValue('server', 'robot')
    print("启动成功："+serverip+":"+serverport)
    try:
        # webbrowser.open("http://127.0.0.1:"+serverport+"/index.html?data="+robot)
        WSGIServer((serverip, int(serverport)), app).serve_forever()
    except OSError as e:
        print("端口被占用")
        kill_process()
        WSGIServer((serverip, int(serverport)), app).serve_forever()